package com.java.Apicontroller;

import com.java.config.result.Result;
import com.java.model.order.PaymentStatusEnum;
import com.java.model.order.PaymentTypeEnum;
import com.java.service.OrderService;
import com.java.service.PayMentInfoService;
import com.java.service.WeixinService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Map;


@Api("微信管理")
@RestController
@RequestMapping("/api/order/weixin")
public class WeixinController {

    @Autowired
    private WeixinService weixinService;

    @Autowired
    private OrderService orderService;

    @Autowired
    private PayMentInfoService payMentInfoService;

    /**
     * 下单 生成二维码
     */
    @ApiOperation("下单生成二维码")
    @GetMapping("/createNative/{orderId}")
    public Result createNative(@PathVariable("orderId") Long orderId){
        return Result.ok(weixinService.createNative(orderId));
    }


    /**
     * 查询下单状态
     */
    @ApiOperation("查询下单状态")
    @GetMapping("/queryPayStatus/{orderId}")
    public Result queryPayStatus(@PathVariable Long orderId){
        //根据orderId 通过去查询微信的接口返回的数据(map)里面的trade_state SUCCESS成功
       Map<String,String> paramMap =  weixinService.queryPayStatus(orderId);
       if(paramMap==null){
           return Result.fail().message("支付错误");
       }
       //查询微信支付的结果 返回得到trade_state 进行判断
       if("SUCCESS".equals(paramMap.get("trade_state"))){
           String outTradeNo = paramMap.get("out_trade_no");
           //支付成功后更改订单的状态 处理支付结果 传入订单的编码 PaymentTypeEnum.WEXIIN.getStatus()  paramMap
           payMentInfoService.paySuccess(outTradeNo,paramMap);
           return Result.ok().message("支付成功");
       }
       return Result.fail().message("支付中");
    }
}
